import { cloneDeep } from 'lodash-es'

export type DicModel = {
  createdBy: string // 创建人
  createdTime: string // 创建时间
  delFlag: 0 | 1 // 是否删除 0:否 1:是
  describe: string // 描述
  dicCode: string //编码
  dicGroupCode: string // 分组编码
  dicGroupName: string // 分组名称
  dicName: string // 名称
  dicStatus: 0 | 1 // 状态 默认为“正常”，1：正常，0：禁用
  dicType: 1 | 2 | 3 // 字典类型（字典类型：1 系统级；2 通用级别；3 自定义）
  id: string // integer(int32)
  orderIndex: string // 排序号
  parentCode: string // 父节点编码
  updatedBy: string // 更新人
  updatedTime: string // 更新时间
}

export type DicTreeModel = {
  id: number // 节点ID
  name: string // 节点名称
  parentId: number // 父节点ID
  rank: string // 排序
  status: 0 | 1 // 状态 0:禁用 1:启用
  children?: DicTreeModel[]
}

export const useDic = (dicModelList: DicTreeModel[], clone = false) => {
  if (clone) dicModelList = cloneDeep(dicModelList)
  const optionMap = new Map<number, DicTreeModel>()

  const recursion = (dicList: DicTreeModel[]) => {
    for (const dic of dicList) {
      optionMap.set(dic.id, dic)
      if (dic.children) recursion(dic.children)
    }
  }
  recursion(dicModelList)

  const getPathIdList = (idList: number[]) => {
    const set = new Set(idList)

    const recursion = (id: number) => {
      const option = optionMap.get(id)
      if (!option) return
      set.add(option.parentId)
      recursion(option.parentId)
    }
    for (const id of idList) {
      recursion(id)
    }

    return [...set]
  }

  const getCheckedIdList = (idList: number[]) => {
    const set = new Set<number>()

    for (const id of idList) {
      const option = optionMap.get(id)
      if (!option || option.children?.length) continue
      set.add(id)
    }

    return [...set]
  }

  return {
    getPathIdList,
    getCheckedIdList
  }
}

const api: ApiConfig = {
  getTree: {
    method: 'GET',
    url: '/sys/dic/getTree'
  },
  infoByCode: {
    method: 'GET',
    url: '/sys/dic/infoByCode/:code'
  },
  info: {
    method: 'GET',
    url: '/sys/dic/info/:id'
  },
  update: {
    method: 'POST',
    url: '/sys/dic/update'
  }
}

export default api
